<template>
  <div class="health-page">
    <van-nav-bar
        title="健康管理"
        left-text="返回"
        left-arrow
        @click-left="router.back()"
    />

    <!-- 健康数据卡片 -->
    <div class="health-cards">
      <div class="card blood-pressure" @click="router.push('/health/records?type=1')">
        <div class="card-header">
          <span class="title">血压</span>
<!--          <van-icon name="arrow" />-->
        </div>
        <div class="card-content" v-if="latestRecords.bloodPressure">
          <div class="value">{{ latestRecords.bloodPressure.recordValue }} mmHg</div>
          <div class="time">{{ formatDateTime(latestRecords.bloodPressure.measureTime) }}</div>
        </div>
        <div class="no-data" v-else>暂无数据</div>
      </div>

      <div class="card blood-sugar" @click="router.push('/health/records?type=2')">
        <div class="card-header">
          <span class="title">血糖</span>
<!--          <van-icon name="arrow" />-->
        </div>
        <div class="card-content" v-if="latestRecords.bloodSugar">
          <div class="value">{{ latestRecords.bloodSugar.recordValue }} mmol/L</div>
          <div class="time">{{ formatDateTime(latestRecords.bloodSugar.measureTime) }}</div>
        </div>
        <div class="no-data" v-else>暂无数据</div>
      </div>

      <div class="card weight" @click="router.push('/health/records?type=3')">
        <div class="card-header">
          <span class="title">体重</span>
<!--          <van-icon name="arrow" />-->
        </div>
        <div class="card-content" v-if="latestRecords.weight">
          <div class="value">{{ latestRecords.weight.recordValue }} kg</div>
          <div class="time">{{ formatDateTime(latestRecords.weight.measureTime) }}</div>
        </div>
        <div class="no-data" v-else>暂无数据</div>
      </div>

      <div class="card temperature" @click="router.push('/health/records?type=4')">
        <div class="card-header">
          <span class="title">体温</span>
<!--          <van-icon name="arrow" />-->
        </div>
        <div class="card-content" v-if="latestRecords.temperature">
          <div class="value">{{ latestRecords.temperature.recordValue }} ℃</div>
          <div class="time">{{ formatDateTime(latestRecords.temperature.measureTime) }}</div>
        </div>
        <div class="no-data" v-else>暂无数据</div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <van-grid :column-num="3" :border="false" :gutter="10" class="quick-actions">
      <van-grid-item @click="router.push('/health/daily')">
        <template #icon>
          <div class="action-icon" style="background-color: #1989fa">
            <van-icon name="plus" size="24" />
          </div>
        </template>
        <template #text>
          <span class="action-text">快捷录入</span>
        </template>
      </van-grid-item>

      <van-grid-item @click="router.push('/health/records')">
        <template #icon>
          <div class="action-icon" style="background-color: #07c160">
            <van-icon name="chart-trending-o" size="24" />
          </div>
        </template>
        <template #text>
          <span class="action-text">健康记录</span>
        </template>
      </van-grid-item>

      <van-grid-item @click="showReport = true">
        <template #icon>
          <div class="action-icon" style="background-color: #ff976a">
            <van-icon name="description" size="24" />
          </div>
        </template>
        <template #text>
          <span class="action-text">健康报告</span>
        </template>
      </van-grid-item>
    </van-grid>

    <!-- 健康提醒 -->
    <van-cell-group inset title="健康提醒" v-if="reminders.length">
      <van-cell
        v-for="item in reminders"
        :key="item.id"
        :title="item.title"
        :label="item.content"
      />
    </van-cell-group>

    <!-- 健康报告弹窗 -->
    <van-popup
      v-model:show="showReport"
      round
      position="bottom"
      :style="{ height: '80%' }"
    >
      <div class="report-popup">
        <div class="popup-header">
          <div class="title">健康报告</div>
          <van-icon name="cross" @click="showReport = false" />
        </div>

        <div class="popup-content">
          <van-loading v-if="reportLoading" />
          <template v-else-if="reportData">
            <!-- 统计数据 -->
            <div class="stats-section">
              <div class="section-title">数据统计</div>
              <div class="stats-grid">
                <div v-for="(avg, type) in reportData.averageValues" :key="type" class="stat-item">
                  <div class="label">{{ getTypeLabel(type) }}</div>
                  <div class="value">{{ avg }}<!--{{ getTypeUnit(type) }}--></div>
                  <div class="sub-label">平均值</div>
                </div>
              </div>
            </div>

            <!-- 分析建议 -->
            <div class="analysis-section">
              <div class="section-title">分析建议</div>
              <div class="analysis-content">{{ reportData.analysis }}</div>
            </div>
          </template>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getLatestRecords, getHealthReport } from '@/api/health'
import { formatDateTime } from '@/utils/format'
import dayjs from 'dayjs'

const router = useRouter()
const latestRecords = ref({})
const reminders = ref([])
const showReport = ref(false)
const reportData = ref(null)
const reportLoading = ref(false)

const loadLatestRecords = async () => {
  try {
    const { data } = await getLatestRecords()
    // 处理数据，按类型分组
    const records = {}
    if (data) {
      data.forEach(record => {
        switch (record.recordType) {
          case 1:
            records.bloodPressure = record
            break
          case 2:
            records.bloodSugar = record
            break
          case 3:
            records.weight = record
            break
          case 4:
            records.temperature = record
            break
        }
      })
    }
    latestRecords.value = records
  } catch (error) {
    console.error('获取数据失败:', error)
    showToast('获取数据失败')
  }
}

const loadHealthReport = async () => {
  try {
    reportLoading.value = true
    const { data } = await getHealthReport({
      startDate: dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
      endDate: dayjs().format('YYYY-MM-DD')
    })
    reportData.value = data
  } catch (error) {
    console.error('获取健康报告失败:', error)
    showToast('获取报告失败')
  } finally {
    reportLoading.value = false
  }
}

// 类型标签映射
const getTypeLabel = (type) => {
  const labels = {
    'bloodPressure': '血压',
    'bloodSugar': '血糖',
    'weight': '体重',
    'temperature': '体温'
  }
  return labels[type] || '未知类型'
}

// 单位映射
const getTypeUnit = (type) => {
  const units = {
    'bloodPressure': 'mmHg',
    'bloodSugar': 'mmol/L',
    'weight': 'kg',
    'temperature': '℃'
  }
  return units[type] || ''
}

onMounted(() => {
  loadLatestRecords()
})

// 监听报告弹窗显示
watch(showReport, (val) => {
  if (val && !reportData.value) {
    loadHealthReport()
  }
})
</script>

<style lang="scss" scoped>
.health-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding: 12px;

  .health-cards {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin-top: 12px;

    .card {
      background: #fff;
      border-radius: 12px;
      padding: 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

      &.blood-pressure { border-top: 4px solid #ee0a24; }
      &.blood-sugar { border-top: 4px solid #07c160; }
      &.weight { border-top: 4px solid #1989fa; }
      &.temperature { border-top: 4px solid #ff976a; }

      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .title {
          font-size: 16px;
          font-weight: 500;
          color: #323233;
        }

        .van-icon {
          color: #969799;
        }
      }

      .card-content {
        .value {
          font-size: 20px;
          font-weight: bold;
          color: #323233;
          margin-bottom: 8px;
        }

        .time {
          font-size: 12px;
          color: #969799;
        }
      }

      .no-data {
        color: #969799;
        font-size: 14px;
        text-align: center;
        margin-top: 12px;
      }
    }
  }

  .quick-actions {
    margin-top: 16px;
    padding: 0 12px;

    .action-icon {
      width: 48px;
      height: 48px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      margin-bottom: 8px;
    }

    .action-text {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }
}

.report-popup {
  height: 100%;
  display: flex;
  flex-direction: column;

  .popup-header {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #eee;

    .title {
      font-size: 18px;
      font-weight: 500;
    }
  }

  .popup-content {
    flex: 1;
    overflow-y: auto;
    padding: 16px;

    .section-title {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 12px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;

      .stat-item {
        background: #f7f8fa;
        padding: 12px;
        border-radius: 8px;

        .label {
          font-size: 14px;
          color: #666;
        }

        .value {
          font-size: 20px;
          font-weight: bold;
          color: #1989fa;
          margin: 4px 0;
        }

        .sub-label {
          font-size: 12px;
          color: #999;
        }
      }
    }

    .analysis-section {
      margin-top: 20px;

      .analysis-content {
        white-space: pre-line;
        line-height: 1.6;
        color: #666;
      }
    }
  }
}
</style>
